<template>
  <div class="address">
    <van-nav-bar
      :title="aid ? '地址编辑' : '新增地址'"
      left-text="返回"
      left-arrow
      @click-left="back"
    />
    <van-address-edit
      :area-list="areaList"
      show-postal
      :show-delete="!!aid"
      show-set-default
      show-search-result
      :detail-maxlength="30"
      :area-columns-placeholder="['请选择', '请选择', '请选择']"
      :address-info="addressInfo"
      @save="onSave"
      @delete="onDelete"
    />
  </div>
</template>

<script>
import areaList from "../assets/js/area";
export default {
  name: "Address",
  data() {
    return {
      areaList,
      aid: "",
      addressInfo: {},
    };
  },
  created() {
    this.aid = this.$route.params.aid;

    if (this.aid) {
      this.getAddressDataByAid();
    }
  },
  methods: {
    back() {
      this.$router.go(-1);
    },

    add(value) {
      let tokenString = this.$cookies.get("tokenString");

      if (!tokenString) {
        console.log("浏览器token不存在");
        return this.$router.push({ name: "Login" });
      }

      //复制value
      let data = {
        ...value,
        tokenString,
        appkey: this.appkey,
      };

      data.isDefault = Number(data.isDefault);
      delete data.country;

      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
      });

      this.axios({
        //请求方式
        method: "POST",
        url: this.baseUrl + "/addAddress",
        data,
      })
        .then((res) => {
          this.$toast.clear();

          if (res.data.code == 700) {
            this.$toast({
              message: res.data.msg,
              forbidClick: true,
              duration: 3000,
            });
            return this.$router.push({ name: "Login" });
          }

          if (res.data.code === 9000) {
            this.$router.push({ name: "AddressList" });
          }

          this.$toast({
            message: res.data.msg,
            forbidClick: true,
            duration: 3000,
          });
        })
        .catch((err) => {
          this.$toast.clear();
          console.log("err ==>", err);
        });
    },
    edit(value) {
      let isEdit = false;

      for (let key in this.addressInfo) {
        if (this.addressInfo[key] !== value[key]) {
          isEdit = true;
          break;
        }
      }
      if (isEdit) {
        let tokenString = this.$cookies.get("tokenString");

        if (!tokenString) {
          console.log("浏览器token不存在");
          return this.$router.push({ name: "Login" });
        }

        let address = {};
        address.aid = this.aid;
        address.name = value.name;
        address.phone = value.phone;
        address.province = value.province;
        address.city = value.city;
        address.county = value.county;
        address.addressDetail = value.addressDetail;
        address.areaCode = value.areaCode;
        address.postalCode = value.postalCode;
        address.isDefault = Number(value.isDefault);
        console.log(address);

        this.$toast.loading({
          message: "加载中...",
          forbidClick: true,
          duration: 0,
        });

        this.axios({
          //请求方式
          method: "POST",
          url: this.baseUrl + "/editAddress",
          data: {
            appkey: this.appkey,
            tokenString,
            ...address,
          },
        })
          .then((res) => {
            // console.log("res edit ==> ", res);
            this.$toast.clear();

            if (res.data.code == 700) {
              this.$toast({
                message: res.data.msg,
                forbidClick: true,
                duration: 3000,
              });
              return this.$router.push({ name: "Login" });
            }

            if (res.data.code === 30000) {
              //如果添加成功, 跳回地址列表组件
              this.$router.push({ name: "AddressList" });
            }

            this.$toast({
              message: res.data.msg,
              forbidClick: true,
              duration: 3000,
            });
          })
          .catch((err) => {
            this.$toast.clear();
            console.log("err ==> ", err);
          });
      } else {
        this.$router.push({ name: "AddressList" });
      }
    },
    onSave(value) {
      if (this.aid) {
        this.edit(value);
      } else {
        this.add(value);
      }
    },
    onDelete(value) {
      let tokenString = this.$cookies.get("tokenString");

      if (!tokenString) {
        console.log("浏览器token不存在");
        return this.$router.push({ name: "Login" });
      }

      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
      });

      this.axios({
        //请求方式
        method: "POST",
        url: this.baseUrl + "/deleteAddress",
        data: {
          tokenString,
          appkey: this.appkey,
          aid: value.aid,
        },
      })
        .then((res) => {
          this.$toast.clear();

          if (res.data.code == 700) {
            this.$toast({
              message: res.data.msg,
              forbidClick: true,
              duration: 3000,
            });
            return this.$toast.push({ name: "Login" });
          }

          if (res.data.code === 10000) {
            this.$router.push({ name: "AddressList" });
          }
          this.$toast({
            message: res.data.msg,
            forbidClick: true,
            duration: 3000,
          });
        })
        .catch((err) => {
          this.$toast.clear();
          console.log("err ==>", err);
        });
    },
    getAddressDataByAid(){
      let tokenString = this.$cookies.get("tokenString");

      if (!tokenString) {
        console.log("浏览器token不存在");
        return this.$router.push({ name: "Login" });
      }

      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
      });

      this.axios({
        //请求方式
        method: "GET",
        url: this.baseUrl + "/findAddressByAid",
        params: {
          appkey: this.appkey,
          tokenString,
          aid: this.aid,
        },
      }).then((res)=>{
        this.$toast.clear();

        if(res.data.code == 700) {
          this.$toast({
            message: res.data.msg,
            forbidClick: true,
            duration: 3000
          });
          return this.$router.push({name:"Login"});
        }

        if(res.data.code === 40000){
          let data = res.data.result[0];
          data.isDefault = !!data.isDefault;

          this.addressInfo = data;
        }else{
          this.$toast({
            message: res.data.msg,
            forbidClick: true,
            duration: 3000
          });
        }
      }).catch((err) =>{
        this.$toast.clear();
        console.log(err);
      })
    }
  },
};
</script>